package middleware

import (
	"encoding/json"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go-project/dto"
	"go-project/pkg/utils"
	"log"
	"net/http"
)

func ErrorMW() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()
		if len(c.Errors) > 0 {
			for _, e := range c.Errors {
				switch e.Type {
				case gin.ErrorTypeBind:
					var jsonErr json.UnmarshalTypeError
					if errors.Is(e.Err, &jsonErr) {
						log.Println("Json binding error")
					}
					errs, ok := e.Err.(validator.ValidationErrors)
					if ok {
						value, exists := c.Get("req_dto")

						if exists {
							getError := dto.GetError(errs, value)
							c.AbortWithStatusJSON(http.StatusOK, utils.Response{
								Code:    utils.ERROR,
								Message: getError,
								Data:    nil,
							})
							return
						}
					}
					status := http.StatusBadRequest
					if c.Writer.Status() != http.StatusOK {
						status = c.Writer.Status()
					}
					c.JSON(status, gin.H{"error": "数据绑定失败"})
				default:
					log.Println("other error")
				}

			}
			if !c.Writer.Written() {
				c.JSON(http.StatusInternalServerError, gin.H{"Error": "internal error"})
			}
		}
	}
}
